package com.zjx.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjx.reggie.common.R;
import com.zjx.reggie.dto.SetmealDto;
import com.zjx.reggie.entity.Setmeal;
import com.zjx.reggie.entity.SetmealDish;
import com.zjx.reggie.mapper.SetmealMapper;
import com.zjx.reggie.service.SetmealDishService;
import com.zjx.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Resource
    private SetmealDishService service;
    @Override
    @Transactional
    public void saveSetmealAndDish(SetmealDto setmealDto) {

        this.save(setmealDto);

        String id = setmealDto.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        if(setmealDto.getId() != null){
            for (int i = 0; i < setmealDishes.size(); i++) {
                setmealDishes.get(i).setSetmealId(id);
            }
        }
        service.saveBatch(setmealDishes);

    }

    @Override
    public SetmealDto getByIdSetmeal(String id) {
        Setmeal setmeal = this.getById(id);

        SetmealDto setmealDto = new SetmealDto();

        if(setmeal != null){
            BeanUtils.copyProperties(setmeal,setmealDto);

            LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
            qw.eq(SetmealDish::getSetmealId,id);

            List<SetmealDish> setmealDishes = service.list(qw);

            setmealDto.setSetmealDishes(setmealDishes);

            return setmealDto;
        }
        return null;

    }

    @Override
    public void updateByIdSetmealDish(SetmealDto setmealDto) {
        this.updateById(setmealDto);

        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,setmealDto.getId());

        service.remove(qw);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        service.saveBatch(setmealDishes);

    }
}
